package com.example.bikemanagerjava.service;

import com.example.bikemanagerjava.entity.User;
import com.example.bikemanagerjava.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public List<User> selectByPage(Integer pageNumber,Integer pageSize,Integer status,String username) {
        Integer skipNumber = (pageNumber - 1) * pageSize;
        return userMapper.selectByPage(skipNumber,pageSize,status,username);
    }
    public int countUsers() {
        return userMapper.countUsers();
    }

    public User selectById(int id) {
        return userMapper.selectById(id);
    }

    public List<User> selectByUserName(String username){
        return userMapper.selectByUserName(username);
    }

    public void deleteUser(int id) {
        userMapper.deleteUser(id);
    }

    public void updateUser(User user) {
        // 查询数据库中原有的数据
        User existingUser = userMapper.selectById(user.getUserId());
        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 合并数据：未传递的字段使用原值
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            user.setUsername(existingUser.getUsername());
        }
        if (user.getPhoneNumber() == null || user.getPhoneNumber().isEmpty()) {
            user.setPhoneNumber(existingUser.getPhoneNumber());
        }
        if (user.getEmail() == null || user.getEmail().isEmpty()) {
            user.setEmail(existingUser.getEmail());
        }
        if (user.getPasswordHash() == null || user.getPasswordHash().isEmpty()) {
            user.setPasswordHash(existingUser.getPasswordHash());
        }
        if (user.getCreatedAt() == null ||user.getCreatedAt().isEmpty()) {
            user.setCreatedAt(existingUser.getCreatedAt());
        }
        if (user.getStatus() == null) {
            user.setStatus(existingUser.getStatus());
        }
        if (user.getLastLoginAt() == null || user.getLastLoginAt().isEmpty()) {
            user.setLastLoginAt(existingUser.getLastLoginAt());
        }
        if (user.getNote() == null || user.getNote().isEmpty()) {
            user.setNote(existingUser.getNote());
        }
        userMapper.updateUser(user);
    }

    public void updateUserStatus(int id, Integer status) {
        userMapper.updateStatusById(id, status);
    }

    public void insertUser(User user) {
        userMapper.insertUser(user);
    }


}
